{% extends "base.html" %}

{% block styles %}
    <style>
        .control-panel {
            margin: 15px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .status-panel {
            margin: 20px;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #f8f9fa;
        }
        #polling-toggle {
            width: 36px;
            height: 36px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }
        #polling-icon {
            font-size: 1.3rem;
        }
        .mb-4 {
        margin-bottom: 0.8rem !important;
        margin-left: 20px;
        }
    </style>
{% endblock %}

{% block content %}
    
    <div class="container mt-4">
        <h3 class="mb-4">控制面板</h3>
        <div class="row">
  
            <div class="col-md-5">
                <div class="control-panel">
                    <h5>机器人控制</h5>
                    <div class="mb-3">
                   
                        <a id="api-help-link" href="#" target="_blank"></a>
                    
                        <select class="form-select" id="robot-cmd" onchange="updateApiHelpLink()">
                            {% for all_apis in robot_all_apis_options %}
                            <option value="{{ all_apis.cmd }}" data-url="{{ all_apis.url }}">{{ all_apis.title }}</option>
                            {% endfor %}
                        </select>
                        
                    </div>

                    <div class="mb-3">
                        <label class="form-label">参数列表</label>
                        <input type="text" class="form-control" id="params" placeholder="p1=v1&p2=v2&p3=v3">
                    </div>
                   
                    <button class="btn btn-lg btn-primary" onclick="doRobotCmd()">
                        执行 <i class="fas fa-paper-plane ms-2"></i>
                    </button>
                    <hr>

                    <button class="btn btn-lg btn-danger" onclick="enterEstop()">
                        进入急停 <i class="fas fa-exclamation-triangle ms-2"></i>
                    </button>

                    <button class="btn btn-lg btn-success" onclick="exitEstop()">
                        退出急停 <i class="fas fa-play ms-2"></i>
                    </button>

                    <button class="btn btn-lg btn-warning" onclick="recharge()">
                        前往充电 <i class="fas fa-plug ms-2"></i>
                    </button>
                 
                </div>
            </div>

            <div class="col-md-4">
                <div class="control-panel">
                    <h5>摄像头控制</h5>
                 <!--
                    <button class="btn btn-lg btn-danger" onclick="startRecording()" disabled>
                        开始录制 <i class="fas fa-circle ms-2"></i>
                    </button>
                    <button class="btn btn-lg btn-warning" onclick="stopRecording()" disabled>
                        停止录制 <i class="fas fa-stop ms-2"></i>
                    </button>
                    <br>
                    <hr>
                 -->
 
               
                    <button class="btn btn-lg btn-info" onclick="takeScreenshot()">
                        拍摄截图 <i class="fas fa-camera ms-2"></i>
                    </button>
                </div>
            </div>

            <div class="col-md-3">
                <div class="control-panel">
                    <h5>升降柱控制</h5>

                        <button class="btn btn-lg btn-danger w-100 mb-2 lift" onclick="sendCommand('move_to_position_three')">
                        移动到三号位 <i class="fa fa-arrow-right" aria-hidden="true"></i>
                        </button>
                        <br><br><br>
                        
                        <button class="btn btn-lg btn-primary w-100 mb-2 lift" onclick="sendCommand('move_to_position_two')">
                        移动到二号位 <i class="fa fa-arrow-right" aria-hidden="true"></i>
                        </button>
                        <br><br><br>

                        <button class="btn btn-lg btn-success w-100 mb-2 lift" onclick="sendCommand('move_to_position_one')">
                        移动到一号位 <i class="fa fa-arrow-right" aria-hidden="true"></i>
                        </button>

                   
                        <!--
                        <button class="btn btn-lg btn-success w-100 mb-2 lift" onclick="sendCommand('move_up')">上升
                        <i class="bi bi-arrow-up ms-2"></i>
                        </button>
                        <button class="btn btn-lg btn-danger w-100 mb-2 lift" onclick="sendCommand('move_down')">下降
                        <i class="bi bi-arrow-down ms-2"></i>
                        </button>
                        <button class="btn btn-lg btn-warning w-100 mb-2 lift" onclick="sendCommand('reset')">复位

                        <i class="bi bi-arrow-counterclockwise ms-2"></i>
                        </button>
                        <button class="btn btn-lg btn-info w-100 mb-2 lift" onclick="sendCommand('stop_moving_up')">停止上升

                        <i class="bi bi-align-top ms-2"></i>
                        </button>
                        <button class="btn btn-lg btn-info w-100 mb-2 lift" onclick="sendCommand('stop_moving_down')">停止下降

                        <i class="bi bi-align-bottom ms-2"></i>
                        </button>
                    -->
                  
                </div>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-5">
                <div class="status-panel">
                    <h5>
                        全局状态
                        <button class="btn btn-lg btn-link btn-sm float-end p-0" onclick="togglePolling()" id="polling-toggle" style="color: inherit;">
                            <i class="bi bi-eye-slash-fill" id="polling-icon"></i>
                        </button>
                    </h5>
                    <pre id="status-info">状态轮询已关闭，点击右上角眼睛图标开启轮询...</pre>
                </div>
            </div>
            <div class="col-md-7">
                <div class="status-panel">
                    <h5>操作状态</h5>
                    <pre id="opt-info">等待获取操作状态...</pre>
                </div>
            </div>
        </div>

        
    </div>
{% endblock %}

{% block scripts %}
    <script>
        // 机器人充电函数 -------------------------------------------------------------
        async function recharge() {

            //if (!confirm('确定要让机器人前往充电站吗？')) {
            //    return;
            //}
            
            const response = await fetch('/api/robot/recharge', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const result = await response.json();
            updateOperationResult({
                ...result,
                container: 'opt-info',
                command: '前往充电'
            });
        }

        // 机器人急停控制函数 -------------------------------------------------------------
        async function enterEstop() {
           // if (!confirm('确定要使机器人进入急停状态吗？')) {
           //     return;
           // }
            
            const response = await fetch('/api/robot/cmd', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    cmd: '/api/estop',
                    params: 'flag=true'
                })
            });
            const result = await response.json();
            updateOperationResult({
                ...result,
                container: 'opt-info',
                command: '进入急停'
            });
        }
        
    

        async function exitEstop() {
           // if (!confirm('确定要退出急停状态吗？')) {
           //     return;
           // }
            
            const response = await fetch('/api/robot/cmd', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    cmd: '/api/estop',
                    params: 'flag=false'
                })
            });
            const result = await response.json();
            updateOperationResult({
                ...result,
                container: 'opt-info',
                command: '退出急停'
            });
        }
        // ---------------------------------------------------------------------------

        // 发送升降柱控制命令 ------------------------------------------------------------
        function sendCommand(command) {
            const buttons = document.querySelectorAll('button.lift');
            buttons.forEach(btn => btn.disabled = true);
            
            fetch(`/api/lift/${command}`, {
                method: 'POST'
            }).then(response => {
                if (response.ok) {
                    return response.json().then(data => {
                        //showToast(`${command} command succeeded`, 'success');
                        updateOperationResult({
                            ...data,
                            container: 'opt-info',
                            command: command 
                        });
                    });
                } else {
                    return response.json().then(data => {
                        updateOperationResult({
                            ...data,
                            container: 'opt-info',
                            command: command 
                        });
                    });
                }
            }).catch(error => {
                updateOperationResult({
                    container: 'opt-info',
                    command: command,
                    error_message: `Network error: ${error.message}`
                });
                console.error('Error:', error);
            }).finally(() => {
                buttons.forEach(btn => btn.disabled = false);
            });
        }
        // ---------------------------------------------------------------------------


        async function doRobotCmd() {
            const cmd = document.getElementById('robot-cmd').value;
            const params = document.getElementById('params').value;
            
            const response = await fetch('/api/robot/cmd', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({cmd, params})
            });
            const result = await response.json();
            updateOperationResult(result);
                
        }
        
        async function startRecording() {
            const response = await fetch('/api/obs/start_recording', {
                method: 'POST'
            });
            const result = await response.json();
            updateOperationResult({
                ...result,
                container: 'opt-info',
                command: '开始录制'
            });
        }
        
        async function stopRecording() {
            const response = await fetch('/api/obs/stop_recording', {
                method: 'POST'
            });
            const result = await response.json();
            updateOperationResult({
                ...result,
                container: 'opt-info',
                command: '停止录制'
            });
        }
        
        async function takeScreenshot(position_info = '') {
            const response = await fetch('/api/obs/screenshot', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ position_info })
            });
            const result = await response.json();
            updateOperationResult({
                ...result,
                container: 'opt-info',
                command: '拍摄截图'
            });
        }
        
        async function updateOperationResult(data) {
            if (data.container === 'opt-info') {
                const optText = `[${new Date().toLocaleString()}] 
Command: ${data.command || 'N/A'}
Status: ${data.status || 'N/A'}
${data.error_message ? 'Error: ' + data.error_message : ''}
${data.results ? 'Data: ' + JSON.stringify(data.results, null, 2) : ''}`;
                
                document.getElementById('opt-info').textContent = optText;
            } else if (data.container === 'status-info') {
                document.getElementById('status-info').textContent = JSON.stringify(data, null, 2);
            }
        }
        
        // 更新API帮助链接
        function updateApiHelpLink() {
            const select = document.getElementById('robot-cmd');
            const selectedOption = select.options[select.selectedIndex];
            const url = selectedOption.dataset.url;
            document.getElementById('api-help-link').href = "/docs/WATER_API.pdf";
        }

        // 初始化时设置帮助链接
        updateApiHelpLink();

        // 定期轮询状态
        let isPolling = false;
        let pollingTimeoutId = null;

        function togglePolling() {
            isPolling = !isPolling;
            const icon = document.getElementById('polling-icon');
            if (isPolling) {
                icon.classList.remove('bi-eye-slash-fill');
                icon.classList.add('bi-eye-fill');
                pollStatus();
                document.getElementById('status-info').textContent = '正在恢复状态轮询...';
            } else {
                icon.classList.remove('bi-eye-fill');
                icon.classList.add('bi-eye-slash-fill');
                if (pollingTimeoutId) {
                    clearTimeout(pollingTimeoutId);
                    pollingTimeoutId = null;
                }
                document.getElementById('status-info').textContent = '状态轮询已暂停';
            }
        }

        async function pollStatus() {
            if (!isPolling) return;
            try {
                const response = await fetch('/api/robot/poll_status');
                const result = await response.json();
                if (result.container === 'status-info') {
                    const statusText = `[${new Date(result.timestamp * 1000).toLocaleString()}] \nCommand: ${result.command}\nStatus: ${result.status}\n${result.error_message ? 'Error: ' + result.error_message : ''}\n${result.results ? 'Data: ' + JSON.stringify(result.results, null, 2) : ''}`;
                    document.getElementById('status-info').textContent = statusText;
                }
                pollingTimeoutId = setTimeout(pollStatus, 1000);
            } catch (error) {
                document.getElementById('status-info').textContent = `Error polling status: ${error.message}`;
                if (isPolling) {
                    pollingTimeoutId = setTimeout(pollStatus, 1000);
                }
            }
        }
        // 启动状态轮询
        // pollStatus();
    </script>
{% endblock %}
